package com.qf.chat.controller;

import com.qf.chat.commons.r.Codes;
import com.qf.chat.commons.r.R;
import com.qf.chat.commons.utils.CodesUtils;
import com.qf.chat.commons.utils.EmailUtils;
import com.qf.chat.entity.User;
import com.qf.chat.service.UserService;
import jakarta.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/email")
@Slf4j
@Validated
public class EmailController {

    @Autowired
    private UserService userService;

    @Autowired
    private EmailUtils emailUtils;

    /**
     * 通过邮件发送验证码
     * @return
     */
    @RequestMapping("/sendCode")
    public R sendCode(@NotBlank(message = "用户名不能为空！") String username){
        log.debug("发送验证码到用户邮箱 - {}", username);

        //根据用户获取用户的邮箱
        User user = userService.queryUserByUserName(username);
        if (user == null) {
            return R.fail(Codes.USER_NOT_FOUND);
        }

        //用户存在
        String email = user.getEmail();
        //验证码
        int codes = (int)(Math.random() * 9000 + 1000);
        //发送邮件
        emailUtils.sendEmailCode(email, codes);

        //将验证码保存到Map集合中
        CodesUtils.putCode(username, codes);

        //返回隐藏后的邮箱地址
        String content = email.substring(3, email.lastIndexOf("@"));
        email = email.replace(content, "******");

        return R.succ(email);
    }
}
